package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.RecommendUserApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TodayBestService {
    @Autowired
    private UserService userService;


    @Value("${tanhua.sso.default.user}")
    private Long tanhuaSsoDefaultUser;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    public TodayBest queryTodayBest(String token) {
        //先解析token
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return null;
        }

        //查询推荐用户（今日佳人）
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
        if(null == todayBest){
            //给出默认的推荐用户
            todayBest = new TodayBest();
            todayBest.setId(tanhuaSsoDefaultUser);
            todayBest.setFateValue(80L); //固定值
        }


        //查询mysql
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());

        if(null == userInfo){
            return null;
        }
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setAge(userInfo.getAge());

        return todayBest;
    }

    public PageResult queryRecommendation(String token, RecommendUserQueryParam param) {
        //先解析token
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        //查询dubbo获取所有的推荐用户
        List<RecommendUser> recommendUsers = this.recommendUserService.queryTodayBestList(user.getId(), param.getPage(), param.getPagesize());
        if (CollectionUtils.isEmpty(recommendUsers)) {
            String[] userStrArray = defaultRecommendUsers.split(",");
            for (String s : userStrArray) {
                RecommendUser recommendUser = new RecommendUser();

                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70, 99));

                recommendUsers.add(recommendUser);
            }

        }

        //获取推荐用户id
        Set<Long> userIds = recommendUsers.stream().map(RecommendUser::getUserId).collect(Collectors.toSet());

        //通过user集合，和参数，封装queryWrapper，查询userInfo
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserInfo::getUserId, userIds);

//        if (StringUtils.isNotEmpty(param.getGender())) {
//            queryWrapper.eq(UserInfo::getSex, StringUtils.equalsIgnoreCase(param.getGender(), "man") ? 1 : 2);
//        }
//        if (StringUtils.isNotEmpty(param.getCity())) {
//            //需要城市参数查询
//            queryWrapper.like(UserInfo::getCity, param.getCity());
//        }
//
//        if (param.getAge() != null) {
//            //设置年龄参数，条件：小于等于
//            queryWrapper.le(UserInfo::getAge, param.getAge());
//        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        if(CollectionUtils.isEmpty(userInfoList)){
            //没有查询到用户的基本信息
            return pageResult;
        }

        List<TodayBest> list = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {

            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());

            for (RecommendUser recommendUser : recommendUsers) {
                if(recommendUser.getUserId().longValue()==userInfo.getUserId().longValue()) {
                    //缘分值
                    double score = Math.floor(recommendUser.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            list.add(todayBest);
        }

        //要将数据按缘分值排序
        Collections.sort(list, ((o1, o2) -> o2.getFateValue().intValue()-o1.getFateValue().intValue()));

        pageResult.setItems(list);
        return pageResult;

    }

    public TodayBest queryTodayBest(Long userId) {
//        //查询推荐用户（今日佳人）
//        TodayBest todayBest = this.recommendUserService.queryTodayBest(userId);
//        if(null == todayBest){
//            //给出默认的推荐用户
//            todayBest = new TodayBest();
//            todayBest.setId(tanhuaSsoDefaultUser);
//            todayBest.setFateValue(80L); //固定值
//        }
//
//
//        //查询mysql
//        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());
//
//        if(null == userInfo){
//            return null;
//        }
//        todayBest.setAvatar(userInfo.getLogo());
//        todayBest.setNickname(userInfo.getNickName());
//        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
//        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
//        todayBest.setAge(userInfo.getAge());
//
//        return todayBest;


        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if(score == 0){
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    @Autowired
    private QuestionService questionService;

    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (null != question) {
            return question.getTxt();
        }
        return "";
    }

    @Value("${tanhua.sso.url}")
    private String url;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.url + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    public List<NearUserVo> queryNearUser(String gender, Integer distance) {
        User user = UserThreadLocal.get();
        //先查询出用户自己的经纬度
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());

        //调用dubbo获取范围内的用户

        List<UserLocationVo> userLocationVos = userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(), userLocationVo.getLatitude(), distance);

        //获取用户的idLIst,并且配合性别进行条件搜索
        Set<Long> userIds = userLocationVos.stream().map(UserLocationVo::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserInfo::getUserId, userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq(UserInfo::getSex, SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.eq(UserInfo::getSex, SexEnum.WOMAN);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            if (userInfo.getUserId().longValue() == user.getId().longValue()) {
                // 排除自己
                continue;
            }
            NearUserVo nearUserVo = new NearUserVo();

            nearUserVo.setUserId(userInfo.getUserId());
            nearUserVo.setAvatar(userInfo.getLogo());
            nearUserVo.setNickname(userInfo.getNickName());
            nearUserVoList.add(nearUserVo);
        }

        //最后返回数据
        return nearUserVoList;
    }

    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;

        List<RecommendUser> recommendUserList = this.recommendUserService.queryTodayBestList(user.getId(), 1, count);
        if (CollectionUtils.isEmpty(recommendUserList)) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);
            }
        }

        List<RecommendUser> records = recommendUserList;
        int showCount = Math.min(10, records.size());

        //洗牌，最多。list.size()次
        Collections.shuffle(records);

        List<RecommendUser> newRecommendUserList = records.subList(0, showCount);


        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecommendUserList) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    public boolean likeUser(Long likeUserId) {

        //先保存
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        //再判断是否相互喜欢
        if(userLikeApi.isMutualLike(user.getId(), likeUserId)){
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
    }
}
